/**
 * Project: springyounger.lottery.web
 * 
 * File Created at 2010-4-12
 * $Id$
 * 
 * Copyright 2009 Zjut Croporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Zjut Edu. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Zjut Edu.
 */
package com.springyouner.lottery.admin;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.springyouner.lottery.tools.LotteryUtil;
import com.springyounger.lottery.dal.dataobject.LotteryPhase;
import com.springyounger.lottery.dal.dataobject.LotteryPrizeQuota;
import com.springyounger.lottery.service.PrizeService;
import com.springyounger.lottery.service.user.PhaseService;

/**
 * AdminPrizeQuotaController
 * 
 * @author springyounger
 */
public class AdminPrizeQuotaController extends MultiActionController {
    private PhaseService phaseService;
    private PrizeService prizeService;

    @SuppressWarnings("unchecked")
    public ModelAndView selectDisplay(HttpServletRequest request, HttpServletResponse response,
                                      String message) throws Exception {
        Map model = new HashMap();
        //当前日期
        Date today = LotteryUtil.getToday();
        List<LotteryPhase> allPhaseList = phaseService.getPhases();
        List<LotteryPhase> phaseList = new ArrayList<LotteryPhase>();
        //得到今天之后的活动列表
        for (LotteryPhase phase : allPhaseList) {
            if (LotteryUtil.getQuot(today, phase.getGmtStart()) > 0) {
                phaseList.add(phase);
            }
        }

        model.put("phaseList", phaseList);
        model.put("message", message);
        return new ModelAndView("admin/quotaList", model);
    }

    /**
     * 显示对应活动的奖品配额
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public ModelAndView prizeDisplay(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        Map model = new HashMap();
        String flag = "";
        String id = request.getParameter("phaseId");

        if (LotteryUtil.isEmpty(id) || !LotteryUtil.isNumeric(id)) {
            return selectDisplay(request, response, "活动id为空");
        }

        int phaseId = Integer.parseInt(id);
        LotteryPhase phase = phaseService.getPhaseById(phaseId);
        int except = phase.getExceptParticiants();

        List<LotteryPrizeQuota> quotaList = prizeService.getAllPrizesByPhaseId(phaseId);

        //设置配额
        for (LotteryPrizeQuota quota : quotaList) {
            //查找每个quota,是否存在
            LotteryPrizeQuota verifyQuota = prizeService.getTopPrizeQuota(quota.getPrizeId());
            //奖品配额设置
            if (null == verifyQuota) {
                //还未创建奖品配额
                flag = "notCreateQuota";
                //默认设置根据奖品级别(百分比)level/100 四舍五入
                BigDecimal amountDecimal = BigDecimal.valueOf(
                        Integer.parseInt(quota.getPrizeLevel()) * except).divide(
                        BigDecimal.valueOf(100), BigDecimal.ROUND_HALF_UP);
                BigDecimal countDecimal = BigDecimal.valueOf(
                        Integer.parseInt(quota.getPrizeLevel()) * except).divide(
                        BigDecimal.valueOf(100), BigDecimal.ROUND_HALF_UP);
                quota.setPrizeAmount(amountDecimal.intValue());
                quota.setAvaliableCount(countDecimal.intValue());
            } else {
                //更新
                flag = "quota";
                quota.setPrizeQuotaId(verifyQuota.getPrizeQuotaId());
                quota.setPrizeAmount(verifyQuota.getPrizeAmount());
                quota.setAvaliableCount(verifyQuota.getAvaliableCount());
            }
        }

        //当前日期
        Date today = LotteryUtil.getToday();
        List<LotteryPhase> allPhaseList = phaseService.getPhases();
        List<LotteryPhase> phaseList = new ArrayList<LotteryPhase>();
        //得到今天之后的活动列表
        for (LotteryPhase tempPhase : allPhaseList) {
            if (LotteryUtil.getQuot(today, tempPhase.getGmtStart()) > 0) {
                phaseList.add(tempPhase);
            }
        }

        model.put("flag", flag);
        model.put("phase", phase);
        model.put("quotaList", quotaList);
        model.put("phaseList", phaseList);
        return new ModelAndView("admin/quotaList", model);
    }

    public ModelAndView insertAndUpdate(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        String message = null;
        //活动
        String id = request.getParameter("id");
        String flag = request.getParameter("flag");

        if (LotteryUtil.isEmpty(id) || !LotteryUtil.isNumeric(id)) {
            message = "活动id为空";
        }

        //数组个数
        String count = request.getParameter("count");
        if (LotteryUtil.isEmpty(count) || !LotteryUtil.isNumeric(count)) {
            return selectDisplay(request, response, "");
        }
        int phaseId = Integer.parseInt(id);
        int arraySize = Integer.parseInt(count);
        //配额数组
        String prizeAmount[] = request.getParameterValues("prizeAmount");
        String avaliableCount[] = request.getParameterValues("avaliableCount");
        String prizeId[] = request.getParameterValues("prizeId");
       
        //检查数组大小
        if (arraySize != prizeAmount.length || arraySize != avaliableCount.length) {
            message = "奖品配额和可用配额数目不相等";
        }

        LotteryPhase phase = phaseService.getPhaseById(phaseId);
        //相差天數
        int quot = LotteryUtil.getQuot(phase.getGmtStart(), phase.getGmtEnd()) + 1;
        //开始时间
        Date startDate = phase.getGmtStart();
        //设置批量数据

        List<LotteryPrizeQuota> quotaList = new ArrayList<LotteryPrizeQuota>();

        for (int i = 0; i < quot; i++) {
            //quot天
            for (int j = 0; j < arraySize; j++) {
                //奖品个数
                LotteryPrizeQuota quota = new LotteryPrizeQuota();
                quota.setPrizeId(Integer.parseInt(prizeId[j])); //prizeId
                quota.setPrizeAmount(Integer.parseInt(prizeAmount[j]));
                quota.setAvaliableCount(Integer.parseInt(avaliableCount[j]));
                quota.setGrantDate(startDate);
                
                quotaList.add(quota);
            }
            //时间加一天
            startDate = LotteryUtil.addDays(startDate, 1);
        }

        if (flag.equals("notCreateQuota")) {
            //批量创建
            if (prizeService.batchInsertPrizeQuota(quotaList)) {
                message = "批量创建配额成功";
            } else {
                message = "批量创建配额失败";
            }
        } else if (flag.equals("quota")) {
            //批量更新
            if (prizeService.batchUpdatePrizeQuota(quotaList)) {
                message = "批量更新配额成功";
            } else {
                message = "批量更新配额失败";
            }
        } else {
            //没有操作
            message = "没有操作";
        }

        return selectDisplay(request, response, message);
    }

    /**
     * @param phaseService the phaseService to set
     */
    public void setPhaseService(PhaseService phaseService) {
        this.phaseService = phaseService;
    }

    /**
     * @param prizeService the prizeService to set
     */
    public void setPrizeService(PrizeService prizeService) {
        this.prizeService = prizeService;
    }
}
